<template>
  <div>
    <div class="select-platform"
         style="margin-top: 30px; margin-left: 30px;"
         v-if="isCreate === true"
    >
      <el-radio-group class="platform-radio" v-model="formType" size="small">
        <el-radio-button :label="1">单个上传</el-radio-button>
        <el-radio-button :label="2">批量上传</el-radio-button>
      </el-radio-group>
      <div style="margin-top: 15px; ">
        <hr style="border: 1px solid rgba(200, 200, 200, 0.3);">
        <br>
      </div>
    </div>
    <template v-if="formType === 1">
      <div class="wrap" v-loading="loading">
        <div class="title-wrap">
          <div class="title" v-if="step === 1">{{ step }}. {{ $t('packet.填写订单信息') }}</div>
          <div class="title" v-else-if="step === 2">{{ step }}. {{ $t('packet.确认订单信息和费用') }}</div>
        </div>
        <div class="content">
          <div class="step" v-if="step === 1">
            <order-form
              :order.sync="order"
              ref="orderForm"
              :disabled-edit-order-id="!isCreate"
            ></order-form>
          </div>
          <div class="step" v-else-if="step === 2">
            <order-detail
              :order="order"
            ></order-detail>
          </div>
        </div>
        <div class="buttons">
          <el-button @click="stepBack()" :type="step <= 1 ? '' : ''" >{{ step > 1 ? $t('packet.上一步') : $t('packet.取消') }}</el-button>
          <!--<el-button type="primary" @click="newSubmitOrder()">{{$t('packet.提交')}}</el-button>-->
          <el-button type="primary" @click="stepForward()">{{ step >= 2 ? $t('packet.提交') : $t('packet.下一步') }}</el-button>
        </div>
        <shipment-fee-dialog
          :visible.sync="shipmentFeeDialogVisible"
          :multiRateData="multiRateData"
          @confirm="confirmShipmentMark"
        ></shipment-fee-dialog>
      </div>
    </template>
    <template v-if="formType === 2">
      <div style="margin-left: 30px; margin-right: 30px;">
        <el-button size="small" type="primary" @click="getBatchUploadPacketOrderTemplate">下载模板</el-button>
        <el-button size="small" type="success" @click="showDrawer">上传记录</el-button>
        <div style="margin-top: 10px; font-size: 14px;">
          请先下载模板，按模板填写订单信息后上传
        </div>
        <div style="margin-top: 10px;">
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
            :headers="uploadHeader"
            :show-file-list="false"
            :on-success="uploadFileSuccess"
            :before-upload="beforeUpload"
            drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将填写好的模板文件拖到此处或<em>点击上传</em></div>
          </el-upload>
        </div>
      </div>
      <el-drawer
        title="上传列表"
        :visible.sync="drawer"
        direction="rtl"
        size="1000px"
      >
        <el-table :data="drawerData">
          <el-table-column
            prop="id"
            label="ID"
            min-width="100"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="fileName"
            :label="$t('stock.file')"
            min-width="200"
            align="center"
          >
            <template slot-scope="{row}">
              <div class="font-blue" style="cursor: pointer" @click="downloadFile(row)">
                {{row.fileName || '-'}}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="statusInfo"
            :label="'状态'"
            min-width="150"
            align="center"
          >
            <template slot-scope="{row}">
              <template v-if="row.status === 'fail'">
                <span class="font-red">{{row.statusStr}} <i class="el-icon-error"></i></span>
              </template>
              <template v-if="row.status === 'waiting'">
                <span class="font-blue">{{row.statusStr}} <i class="el-icon-loading"></i></span>
              </template>
              <template v-if="row.status === 'handling'">
                <span class="font-blue">{{row.statusStr}} <i class="el-icon-loading"></i></span>
              </template>
              <template v-if="row.status === 'success'">
                <span class="font-green">{{row.statusStr}} <i class="el-icon-success"></i></span>
              </template>
            </template>
          </el-table-column>
          <el-table-column
            prop="numInfo"
            :label="'处理结果'"
            min-width="150"
            align="center"
          >
            <template slot-scope="{row}">
              <template v-if="row.status === 'fail'">
                <span>—</span>
              </template>
              <template v-if="row.status === 'waiting'">
                <span>—</span>
              </template>
              <template v-if="row.status === 'handling'">
                <span>{{row.successNum}}/{{row.allNum}}</span>
              </template>
              <template v-if="row.status === 'success'">
                <span>
                  <span class="font-red" v-if="row.successNum !== row.allNum">{{row.successNum}}</span><span v-else>{{row.successNum}}</span>/{{row.allNum}}
                </span>
              </template>
            </template>
          </el-table-column>
          <el-table-column
            prop="isFailShow"
            :label="'失败原因'"
            min-width="100"
            align="center"
          >
            <template slot-scope="{row}">
              <template v-if="row.isFailShow === true">
                <el-button type="text" style="color: red;" @click="showFailData(row)">查看</el-button>
              </template>
              <template v-else>
                <span>—</span>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </el-drawer>
    </template>
  </div>
</template>

<script>
import {
  checkPacketOrderRepeat, getMultiRate, getPacketOrderExpectInfo, getPacketOrderInfo, savePacketOrder, getBatchUploadPacketOrderList,getBatchUploadPacketOrderTemplate
} from "@/api/packetOrders";
import OrderForm from "@/views/packetOrders/components/OrderForm.vue";
import ShipmentFeeDialog from "@/views/packetOrders/components/ShipmentFeeDialog.vue";
import {deepClone} from "@/utils";
import OrderDetail from "@/views/packetOrders/components/OrderDetail.vue";
import {getToken} from "@/utils/auth";


export default {
  components: {OrderDetail, ShipmentFeeDialog, OrderForm},
  data() {
    return {
      isCreate: true,
      loading: false,
      order: {
        orderId: '',
        goodsData: [],
        packetWeight: '',
        packetLength: '',
        packetWidth: '',
        packetHeight: '',
        confirmationCode: 'None',
        buyerName: '',
        buyerPhone: '',
        buyerPostalCode: '',
        buyerState: '',
        buyerStateCode: '',
        buyerCity: '',
        buyerAddress: '',
        remark: '',
        shipmentMark: '',
        // 贴单单价
        spStickerPrice: '',
        // 续件
        totalStickerAppend: '',
        // 快递加收
        logisticTypePrice: '',
        // 包装费用
        packageMaterialPrice: '',
        // 总价
        totalFee: '',
        shippingType: 0, // 0: 无面单 1: 平台面单
        pdfPath: '', // pdf文件
        isAddressOperation: true,
        operationBuyerState: '',
        operationBuyerCity: '',
      },
      step: 1,
      shipmentFeeDialogVisible: false,
      multiRateData: [],
      expectInfo: null,
      formType: 1,
      uploadUrl: process.env.VUE_APP_BASE_API + '/packetOrders/batchUploadPacketOrderInfo',
      uploadHeader: {
        Authorization: 'Bearer ' + getToken(),
      },
      drawer: false,
      drawerData: [],
      drawerParams: {
        page: 1,
        drawerType: 'order',
      },
      interval: null,
      exportTemplate: '',
    }
  },
  computed: {
    isInterval(){
      return this.drawerData.some(item=>{
        if(item.status === 'waiting' || item.status === 'handling'){
          return true
        }
        return false
      })
    },
  },
  created() {
    // 根据参数判断是新增还是更新
    if (this.$route.query.orderId) {
      this.isCreate = false;
      this.getOrderInfo(this.$route.query.orderId);
    } else {
      this.isCreate = true;
    }
    this.interval = setInterval(()=>{
      // 请求数量 但没有loading效果
      if(this.isInterval && this.drawer){
        this.getDrawerData()
      }
    },1500)
  },
  methods: {
    getOrderInfo(orderId) {
      this.loading = true;
      getPacketOrderInfo(orderId)
        .then(res => {
          this.order = res.data.packetOrder;
          this.order.spStickerPrice = res.data.packetOrder.preSpStickerPrice;
          this.order.totalStickerAppend = res.data.packetOrder.preStickerAppend;
          this.order.logisticTypePrice = res.data.packetOrder.preLogisticTypePrice;
          this.order.packageMaterialPrice = res.data.packetOrder.prePackingCharge;
          this.order.totalFee = this.order.spStickerPrice + this.order.totalStickerAppend + this.order.logisticTypePrice + this.order.packageMaterialPrice;
          this.loading = false;
        })
    },
    stepForward() {
      if (this.step >= 2) {
        this.newSubmitOrder();
      } else if (this.step <= 1) {
        this.newCheckOrder();
      }
    },
    stepBack() {
      if (this.step <= 1) {
        this.$router.push('/packetOrders');
      } else {
        this.step--;
      }
    },
    // 获取预估信息
    getPacketOrderExpectInfo() {
      this.loading = true;
      getPacketOrderExpectInfo(this.order)
        .then(res => {
          this.expectInfo = res.data;
          this.order = {...this.order, ...this.expectInfo};
          this.step++;
          this.loading = false;
        })
          .catch(error => {
            this.loading = false;
          })
    },
    confirmShipmentMark(shipmentMark) {
      this.shipmentFeeDialogVisible = false;
      this.order.shipmentMark = shipmentMark;
      this.getPacketOrderExpectInfo()
    },
    // 获取多种运费
    getMultiRateData() {
      this.loading = true;
      getMultiRate(this.order)
          .then(res => {
            this.loading = false;
            this.multiRateData = res.data;
            this.shipmentFeeDialogVisible = true;
          })
          .catch(error => {
            this.loading = false;
          })
    },
    // 检查订单是否有问题
    checkOrder() {
      this.$refs.orderForm.checkForm()
          .then(() => {
            if (this.isCreate) {
              this.order = deepClone(this.$refs.orderForm.computedOrder);
              // console.log('this.order', this.order);
              this.loading = true;
              checkPacketOrderRepeat({orderId: this.order.orderId})
                  .then(res => {
                    console.log('res', res);
                    this.loading = false;
                    this.getMultiRateData();
                  })
                  .catch(error => {
                    this.loading = false;
                  });
            } else {
              this.getMultiRateData();
            }
          })
          .catch((error) => {
            console.log('form error', error);
          });
    },
    // 提交
    submitOrder() {
      this.loading = true;
      savePacketOrder(this.order)
          .then(res => {
            this.loading = false;
            if (res.error === 0) {
              this.$message.success(this.$t('packet.操作成功'));
              this.$router.push('/packetOrders');
            } else {
              this.$errorMessage(res.message);
            }
          })
          .catch(error => {
            this.loading = false;
          })
    },
    // 提交
    newSubmitOrder() {
      this.loading = true;
      savePacketOrder(this.order)
        .then(res => {
          this.loading = false;
          if (res.error === 0) {
            this.$message.success(this.$t('packet.操作成功'));
            this.$router.push('/packetOrders');
          } else {
            this.$errorMessage(res.message);
          }
        })
        .catch(error => {
          this.loading = false;
        })
    },
    // 检查订单是否有问题
    newCheckOrder() {
      this.$refs.orderForm.checkForm()
        .then(() => {
          this.order = deepClone(this.$refs.orderForm.computedOrder);
          // console.log('this.order', this.order);
          if (!this.isCreate) {
            this.order.isSave = true
          }
          this.loading = true;
          checkPacketOrderRepeat(this.order)
            .then(res => {
              this.order.spStickerPrice = res.info.totalFeeArr.spStickerPrice
              this.order.totalStickerAppend = res.info.totalFeeArr.stickerAppend
              this.order.logisticTypePrice = res.info.totalFeeArr.logisticTypePrice
              this.order.packageMaterialPrice = res.info.totalFeeArr.packingCharge
              this.order.totalFee = res.info.totalFeeArr.totalFee
              console.log(this.order)
              this.loading = false;
              this.step++
            })
            .catch(error => {
              this.loading = false;
            });
        })
        .catch((error) => {
          console.log('form error', error);
        });
    },

    getBatchUploadPacketOrderTemplate(){
      getBatchUploadPacketOrderTemplate()
        .then(response =>{
          // 创建 Blob 对象
          const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });

          // 创建文件对象 URL
          const excelFile = window.URL.createObjectURL(blob);

          // 创建下载链接
          const link = document.createElement('a');
          link.href = excelFile;
          link.download = '批量上传小包订单.xlsx';  // 文件名可自定义
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);

          // 释放URL对象
          setTimeout(() => {
            URL.revokeObjectURL(excelFile);
          }, 60000); // 60秒后释放
        })
    },

    uploadFileSuccess(res, file) {
      if (res.error === 0) {
        this.$successMessage(res.message)
        this.showDrawer()
      } else {
        this.$errorMessage(res.message);
      }
    },

    beforeUpload(){
      return true
    },

    showDrawer() {
      this.drawer = true
      this.drawerParams.page = 1;
      this.getDrawerData()
    },

    getDrawerData() {
      getBatchUploadPacketOrderList()
        .then(res => {
          this.drawerData = res.data;
        })
    },

    downloadFile(row) {
      if(!row.filePath){
        return
      }
      window.open(row.filePath,"_blank");
    },

    showFailData(row) {
      //跳转页面查看错误数据
      let routeUrl = this.$router.resolve({
        name: 'batchUploadPacketErrorData',
        query: {
          'id': row.id,
          'type': 'order',
        }
      })
      // 新标签打开路由
      window.open(routeUrl.href, '_blank');
    },
  },
  beforeDestroy() {
    if (this.interval) {
      clearInterval(this.interval)
    }
  },
}
</script>

<style>
.platform-radio{
.el-radio-button__inner{

}
.el-radio-button__inner:hover {
  color: #ff6d6d;
}
.el-radio-button__orig-radio:checked + .el-radio-button__inner {
  color: #FFFFFF;
  background-color: #ff6d6d;
  border-color: #ff6d6d;
  -webkit-box-shadow: -1px 0 0 0 #ff6d6d;
  box-shadow: -1px 0 0 0 #ff6d6d;
}
}
</style>

<style scoped lang="less">
.form{
  padding: 20px;
  @imageWidth: 100px;
  .image{
    display: block;
    width: @imageWidth;
    min-height: @imageWidth;
    margin-top: 16px;
    background: lightgray;
  }
  .tips{
    color: #999;
    font-size: 12px;
    margin-top: 5px;
  }
  .goodsNumInBox{
    display: flex;
  }
  .goodsValue{
    display: flex;
  }
  .isCombination{
    display: flex;
  }
  .size-input{
    width: 100px;
    ::v-deep .el-input-group__append{
      padding: 0 15px !important;
    }
  }
  .size-input-box{
    display: flex;
    flex-direction: row;
    justify-content: space-between;
  }
}
.block{
  width: 600px;
  .title{
    font-size: 16px;
    font-weight: bold;
    padding: 0 0 12px;
  }
}
.buttons{
  margin-top: 30px;
}
</style>

<style scoped lang="less">
.wrap{
  padding: 30px;
}
.title-wrap{
  padding: 0 0 30px;
}
.content{
  padding: 0 32px;
}
</style>
